import axios from 'axios'
import { toastMsg } from "@/lib/toast";


const baseURL = import.meta.env.VITE_API_URL || ""

const service = axios.create({
  baseURL: baseURL,
})

// 添加请求拦截器
service.interceptors.request.use(
  function (config) {

    const token = localStorage.getItem('custom_api_token')
    if (token) {
      try {
        const tk = JSON.parse(token)
        config.headers[tk.header] = `${tk.token}`;
      } catch (error) {
      }
    }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use(
  function (response) {
    if (response.status !== 200) {
      toastMsg.error('请求失败')
      return Promise.reject(new Error('请求失败'))
    }
    if (response.data instanceof Blob) {
      return response
    }
    if (response.data.code === 3000) {
      toastMsg.error(response.data.msg || '请求失败')
    }
    if (response.data.code !== 200) {
      toastMsg.error(response.data.msg || '请求失败')
      return Promise.reject(new Error('请求失败'))
    }
    return response.data
  },
  function (error) {
    if (error.code === 'ERR_NETWORK') {
      toastMsg.error('网络异常，请检查网络连接')
      return Promise.reject(error)
    }
    const { msg } = error?.response?.data
    toastMsg.error(msg)
    return Promise.reject(error)
  }
)

function transformRequest() {
  return [
    function (data: { [x: string]: string | number | boolean }) {
      let ret = ''
      for (const it in data) {
        if (data[it] !== null) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
      }
      return ret
    },
  ]
}

function headers() {
  return { 'Content-Type': 'application/x-www-form-urlencoded' }
}

service.transformRequest = transformRequest()
service.headers = headers()

export default service
